#coding:utf-8

from flask import Blueprint, request, session, redirect, url_for, render_template, flash
from service.orderservice import oservice
from model.userinfo import UserInfo

oc = Blueprint("ordercontroller", __name__, template_folder="html")

@oc.route("/add", methods=["GET"])
def add_html():
	user = None
	if "user" in session:
		user = UserInfo()
		user.uname = session["user"]
	return render_template("add.html", user=user)

@oc.route("/add", methods=["POST"])
def add():
	what = request.values.get("what")
	amount = request.values.get("amount")

	print(what)
	if not what:
		flash("you buy what?")
		return redirect(url_for("ordercontroller.add_html"))
	if not amount:
		flash("you spent how much")
		return redirect(url_for("ordercontroller.add_html"))

	user = UserInfo()
	user.uname = session["user"]
	who = user.uname
	#whoid = user.uid

	if oservice.add_order(who, what, amount) == 1:
		return redirect(url_for("first"))
	return "error"

@oc.route("/history", methods=["GET"])
def history():
	user = None
	if "user" in session:
		user = UserInfo()
		user.uname = session["user"]
	res = oservice.get_all()
	return render_template("history.html", orderList = res, user=user)

@oc.route("/accept")
def accept():
	user = None
	if "user" in session:
		user = UserInfo()
		user.uname = session["user"]
	id = request.values.get("id")
	audit_status = request.values.get("s")
	where = ""
	where = request.values.get("w")
	res = oservice.update_order(id, audit_status)
	print(res)
	if res == 0:
		flash("error")
	if where == "h":
		res = oservice.get_all()
		return render_template("history.html", orderList = res, user=user)
	res = oservice.get_all_today()
	return render_template("index.html", orderList = res, user=user)


	